package clsr.info.blog.common.event;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

@Component
public class EventPublisher {
  @Autowired private EventServiceFactory eventServiceFactory;
  private Queue eventQueue = new LinkedBlockingQueue();

  @Async
  public void emit(BaseEvent baseEvent) {
    this.eventQueue.offer(baseEvent);
  }

  @Scheduled(fixedRate = 500)
  public void dealWithEvent() {
    Object obj = this.eventQueue.poll();
    if (obj != null) {
      BaseEvent event = (BaseEvent) obj;
      EventService eventService = this.eventServiceFactory.getInstance(event.getEventEnum());
      eventService.dealWithEvent(event);
    }
  }
}
